package cn.tannn.ops.backup.service.impl;


import cn.tannn.jdevelops.exception.built.BusinessException;
import cn.tannn.jdevelops.jpa.service.J2ServiceImpl;
import cn.tannn.ops.backup.constant.DbType;
import cn.tannn.ops.backup.dao.DbBackupDao;
import cn.tannn.ops.backup.entity.DbBackup;
import cn.tannn.ops.backup.model.SshRemoteFile;
import cn.tannn.ops.backup.service.DbBackupService;
import cn.tannn.ops.ssh.entity.SshInfo;
import cn.tannn.ops.util.DbUtil;
import cn.tannn.ops.util.SSHUtil;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据库备份
 *
 * @author tnnn
 * @version V1.0
 * @date 2024-9-10
 */
@Slf4j
@Service
public class DbBackupServiceImpl extends J2ServiceImpl<DbBackupDao, DbBackup, Long> implements DbBackupService {

    public DbBackupServiceImpl() {
        super(DbBackup.class);
    }

    @Override
    @Async("applicationTaskExecutor")
    public void backup(DbBackup db, SshInfo ssh) {
        Session session = null;
        try {
            if(!db.getDbType().equals(DbType.MYSQL)){
                throw new BusinessException("暂不支持["+db.getName()+"]类型的数据库备份");
            }
            session = SSHUtil.connectionServer(ssh.getUsername(), ssh.getPassword(), ssh.getUrl(), ssh.getPort());
            String remoteFile = DbUtil.mysqlDumpBackup(session, db.getUser(), db.getPassword(), db.getHost()
                    , db.getPort()
                    , db.getDbName()
                    , db.getDumpPath()
                    , db.getRemoteBackupPath());
            log.info("Backup file successfully , file path is " + remoteFile);
        } catch (Exception e) {
            log.error("Backup file failed", e);
            throw new BusinessException(db.getDbName() + "--> 数据库备份失败", e);
        } finally {
            SSHUtil.disconnectServer(session);
        }
    }

    @Override
    public List<SshRemoteFile> findBackupFiles(DbBackup db, SshInfo ssh) {
        try {
            Session session = SSHUtil.connectionServer(ssh.getUsername(), ssh.getPassword(), ssh.getUrl(), ssh.getPort());
            return SSHUtil.getRemoteFileList(session, db.getRemoteBackupPath());
        } catch (Exception e) {
            log.error("Backup file failed", e);
        }
        return new ArrayList<>();
    }

}
